/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller;

import com.thienloc.omap.entity.RequestQueue;
import com.thienloc.omap.entity.ServiceSuggestion;
import com.thienloc.omap.jdbc.dao.TblSmsBroadcastingDao;
import com.thienloc.omap.jdbc.entity.TblSmsBroadcasting;
import com.thienloc.omap.service.broadcast.BroadcastService;
import com.thienloc.omap.session.RequestQueueFacade;
import com.thienloc.omap.session.ServiceSuggestionFacade;
import com.thienloc.omap.util.JsfUtil;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
@ManagedBean
@ViewScoped
public class RequestQueueSuggestBean extends BaseBean implements Serializable {

    @EJB
    private RequestQueueFacade requestQueueFacade;
    @EJB
    private ServiceSuggestionFacade serviceSuggestionFacade;
    private List<RequestQueue> list;
    private final int MAX_RESULT = 250;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final String STATUS_NEED_TO_HELP = "NEED_TO_HELP";
    private final String STATUS_SENDING_HELP = "SENDING_HELP";
    private final String STATUS_COMPLETED = "COMPLETED";
    private Map<String, String> helpContentMap;

    @PostConstruct
    void init() {
        List<String> statusesToSearch = new ArrayList<String>();
        statusesToSearch.add(STATUS_NEED_TO_HELP);

        list = requestQueueFacade.findByStatus(statusesToSearch, MAX_RESULT, true);

        for (RequestQueue requestQueue : list) {
            requestQueue.setSelectTime(new Date());
        }
    }

    public List<String> completeFullCommand(String query) {
        try {
            return serviceSuggestionFacade.findAllAlikeFullCommand(query);
        } catch (Exception ex) {
            String error = "Lỗi! ";
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage(error, ex.getMessage());
            return new ArrayList<String>(0);
        }
    }

    public void onChangeFullCommand(String fullCommand) {
        try {
            List<ServiceSuggestion> serviceSuggestions = serviceSuggestionFacade.findByFullCommand(fullCommand);
            helpContentMap = new TreeMap<String, String>();
            for (ServiceSuggestion serviceSuggestion : serviceSuggestions) {
                helpContentMap.put(serviceSuggestion.getShortHelpContent(), serviceSuggestion.getHelpContent());
            }
        } catch (Exception ex) {
            String error = "Lỗi! ";
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage(error, ex.getMessage());
        }
    }

    private void updateRequestStatus(RequestQueue request, String status) throws Exception {
        request.setStatus(status);
        request.setLastCheckTime(new Date());
        requestQueueFacade.edit(request);
    }

    public void updateAll() {
        try {
            if (!list.isEmpty()) {
                int cnt = 0;

                TblSmsBroadcastingDao tblSmsBroadcastingDao = new TblSmsBroadcastingDao();
                BroadcastService broadcastService = new BroadcastService();
                broadcastService.connect();

                for (RequestQueue request : list) {
                    try {
                        RequestQueue rq = requestQueueFacade.find(request.getRequestId());

                        if ((rq.getStatus() != null && !rq.getStatus().equals(STATUS_SENDING_HELP))) {
                            updateRequestStatus(request, STATUS_SENDING_HELP);//thuc hien update vao Db
                            logger.info("[{}] {}: Updated to SENDING_HELP: \"{}\"", new Object[]{getUsername(), request.getMsisdn(), request.getRequestDetail()});

                            try {
                                StringBuilder sb = new StringBuilder();
                                int seq = sessionBean.getBroadcastInstantSeq();
                                sb.append(seq);//????
                                sb.append(";");
                                sb.append(request.getMsisdn());
                                sb.append(";");
                                sb.append(request.getCpNumber());
                                sb.append(";");
                                sb.append(request.getHelpContent());
                                sb.append(";");
                                sb.append(request.getDeliverProvider());
                                sb.append("|");
                                broadcastService.send(sb.toString());
                                logger.info("[{}] Sent to BroadcastService: {}", getUsername(), sb.toString());
                            } catch (IOException ex) {
                                updateRequestStatus(request, STATUS_NEED_TO_HELP);
                                String error = "Lỗi! ";
                                logger.error("[{}]: ", getUsername(), ex);
                                JsfUtil.addErrorMessage(error, ex.getMessage());
                            }

                            try {
                                TblSmsBroadcasting tblSmsBroadcasting = new TblSmsBroadcasting();
                                tblSmsBroadcasting.setSc(request.getCpNumber());
                                tblSmsBroadcasting.setMsisdn(request.getMsisdn());
                                tblSmsBroadcasting.setProvider(request.getDeliverProvider());
                                tblSmsBroadcasting.setResult("OK");
                                tblSmsBroadcasting.setSms(request.getHelpContent());
                                tblSmsBroadcasting.setSentTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                tblSmsBroadcastingDao.add(tblSmsBroadcasting);
                            } catch (SQLException ex) {
                                String error = "Lỗi! ";
                                logger.error("[{}]: ", getUsername(), ex);
                                JsfUtil.addErrorMessage(error, ex.getMessage());
                            }

                            updateRequestStatus(request, STATUS_COMPLETED);

                            cnt++;
                        } else {
                            logger.info("[{}] {}: Request status SENDING_HELP", getUsername(), request.getMsisdn());
                        }
                    } catch (Exception ex) {
                        String error = "Lỗi! ";
                        logger.error("[{}]: ", getUsername(), ex);
                        JsfUtil.addErrorMessage(error, ex.getMessage());
                    }
                }
                if (cnt > 0) {
                    JsfUtil.addSuccessMessage("Thành công!", "Đã gửi tin nhắn tới " + cnt + " số ");
                }
            }

            init();
        } catch (Exception ex) {
            String error = "Lỗi! ";
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage(error, ex.getMessage());
        }
    }

    public Map<String, String> getHelpContentMap() {
        return helpContentMap;
    }

    public List<RequestQueue> getList() {
        return list;
    }
}
